//
//  VideoViewController.m
//  NBNews
//
//  Created by Ruan on 14-10-8.
//  Copyright (c) 2014年 Hero. All rights reserved.
//

#import "VideoViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "MJRefresh.h"
#import "MediaTableViewCell.h"
#import "VideoPlayer.h"
#import <MediaPlayer/MediaPlayer.h>

#import "SettingViewController.h"


#define Media_Play @"http://c.m.163.com/nc/video/list/V9LG4B3A0/n/"
static int number = 10;
static int alertnum = 1;


@interface VideoViewController ()

@end

@implementation VideoViewController

- (void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [_mediaArray release];
    [super dealloc];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    //下拉刷新
    [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    //上拉加载
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark 进入刷新状态
- (void)headerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * headerUpdataString =[Media_Play stringByAppendingFormat:@"%d-10.html",0];
        [self requestWebDataForURLString:headerUpdataString andIsDowndrag:YES];
    });
}
- (void)footerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * footerUpdateString = [Media_Play stringByAppendingFormat:@"%d-10.html",number];
        [self requestWebDataForURLString:footerUpdateString andIsDowndrag:NO];
    });
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.mediaArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoPlayer * media = [_mediaArray objectAtIndex:indexPath.row];
    NSString * identifier = @"mediaCell";
    MediaTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[MediaTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
    }
    cell.media = media;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 250;
}

#pragma 网络请求
- (void)tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_mediaArray == nil) {
        _mediaArray = [[NSMutableArray alloc]init];
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}
- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = responseObject;
        NSArray *keyarray = [dict allKeys];
        NSString *keyString = keyarray[0];
        NSArray *techArray = [dict objectForKey:keyString];
        for (NSDictionary *dict in techArray) {
            VideoPlayer * media = [[VideoPlayer alloc] init];
            [media setValuesForKeysWithDictionary:dict];
            [requestDataArray addObject:media];
            [media release];
        }
        if (isDowndrag) {
            self.mediaArray = requestDataArray;
            [self.tableView headerEndRefreshing];
            number = 10;
        }else
        {
            [self.mediaArray addObjectsFromArray:requestDataArray];
            number += 10;
            [self.tableView footerEndRefreshing];
        }
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UILabel * textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];
        [textLable release];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
    }];
    [requestDataArray release];
}
#pragma 点击播放视屏---------------------------------------------------------------
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //设置播放器
    VideoPlayer * media = [_mediaArray objectAtIndex:indexPath.row];
    NSURL * mediaUrl =  [NSURL URLWithString:media.mp4_url];
    MPMoviePlayerViewController * player = [[MPMoviePlayerViewController alloc]initWithContentURL:mediaUrl];
    player.moviePlayer.scalingMode = MPMovieScalingModeAspectFit;
    //查看wifi模式是否开启
    NSUserDefaults * defaults =  [NSUserDefaults standardUserDefaults];
    NSString * wifistate = [defaults objectForKey:@"on"];
    
    // 1.检测wifi状态
    Reachability *wifi = [Reachability reachabilityForLocalWiFi];
    // 2.检测手机是否能上网络(WIFI\3G)
    Reachability *conn = [Reachability reachabilityForInternetConnection];
    if ([wifistate isEqualToString:@"1"]) {
        // 3.判断网络状态
        if ([wifi currentReachabilityStatus] != NotReachable) { // 有wifi
            
            [self presentMoviePlayerViewControllerAnimated:player];
            [player.moviePlayer play];
            
        } else{
            if ([conn currentReachabilityStatus] == ReachableViaWWAN) {
                UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"视频会产生大量流量,建议您开启wifi浏览" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                [alter show];
                [alter release];
            }else{
                
                UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"警告" message:@"当前网络不可用" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
                [alter show];
                [alter release];
            }
        }
    }else{
        if ([conn currentReachabilityStatus] != NotReachable) {
            [self presentMoviePlayerViewControllerAnimated:player];
            [player.moviePlayer play];
            
        }else{
            UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"警告" message:@"当前网络不可用" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles: nil];
            [alter show];
            [alter release];
        }
    }
   [player release];
}

- (void)viewWillAppear:(BOOL)animated
{
    if (alertnum == 1) {
    
        [super viewWillAppear:YES];
        UIAlertView * alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"在2G/3G网络下视频会产生大量流量,建议在WIFI网络下浏览" delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil];
        [alter show];
        [alter release];
        alertnum = 0;
    }
}

@end
